package com.whut.cristiano.autographbook.Model;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ykbboom on 2017/2/23 16:13
 * email：ykbpro@whut.edu.cn
 */

public class GsonRequest<T> extends Request<T> {
//    /** Default charset for JSON request. */
//    protected static final String PROTOCOL_CHARSET = "utf-8";
//
//    /** Content type for request. */
//    protected final String PROTOCOL_CONTENT_TYPE =
//            String.format("application/json; charset=%s", PROTOCOL_CHARSET);

    private Gson gson;
    private Class<T> mclass;
    private Response.Listener<T> mlistener;
    private Map<String,String> params;

    public GsonRequest(int method, String url, Map<String,String> params, Class<T> mclass, Response.Listener<T> mlistener,
                         Response.ErrorListener errorListener) {
        super(method, url, errorListener);
        this.params = params;
        this.gson = new Gson();
        this.mlistener = mlistener;
        this.mclass = mclass;
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse networkResponse) {
        try {
            String json = new String(networkResponse.data,
                    HttpHeaderParser.parseCharset(networkResponse.headers));
            return Response.success(gson.fromJson(json,mclass),
                    HttpHeaderParser.parseCacheHeaders(networkResponse));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected void deliverResponse(T t) {
        mlistener.onResponse(t);
    }

    /*
    @Override
    public Map<String, String> getHeaders() {
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("Accept","application/json");
        headers.put("Content-Type","application/json;charset=UTF-8");

        return headers;
    }*/
    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return params==null?new HashMap<String, String>():params;
    }
    /*
    @Override
    public String getBodyContentType() {
        return PROTOCOL_CONTENT_TYPE;
    }*/

}
